$(document).ready(function() {
    // 默认显示全部排行
    showRankings('weekly');
    $('#weekly').addClass('active');

    // 点击按钮切换排行榜类型
    $('.rank-button').click(function() {
        // 移除所有按钮的高亮类
        $('.rank-button').removeClass('active');
        // 为点击的按钮添加高亮类
        $(this).addClass('active');
    });

    $('#weekly').click(function() {
        showRankings('weekly');
    });

    $('#monthly').click(function() {
        showRankings('monthly');
    });

    $('#likes').click(function() {
        showRankings('likes');
    });

    $('#hot').click(function() {
        showRankings('hot');
    });

    $('#total').click(function() {
        showRankings('total');
    });

    // 根据类型获取相应的排行榜数据并显示
    function showRankings(type) {
        $.ajax({
            url: '/movie-rank/' + type,
            method: 'GET',
            success: function(data) {
                displayRankingList(data.records)
            },
            error: function(xhr, status, error) {
                console.error('Error:', error);
            }
        });
    }

    function displayRankingList(records) {
        const movieList = $("#rankings-list");
        movieList.empty();
        var movieNum = 1;

        records.forEach(record => {
            const movieDiv = $("<div>").addClass("movie").attr("id", record.movie.cover);
            const imageUrl = `/img/cover/c` + `${record.movie.cover}.webp`;
            const img = $("<img>").attr("src", imageUrl).attr("alt", record.movie.title).css({
                "width": "200px",
                "height": "280px",
                "object-fit": "cover",
                "border-radius": "5px"
            });
            movieDiv.append($("<span>").addClass("movie-rank").text(movieNum));
            movieNum++;
            movieDiv.append(img);
            movieDiv.append($("<h3>").text(record.movie.title));
            movieDiv.append($("<p>").text(`类型: ${record.movie.type}`));
            movieDiv.append($("<p>").text(`地区: ${record.movie.region}`));
            movieDiv.append($("<p>").text(`演员: ${record.movie.actors}`));
            movieDiv.append($("<p>").text(record.movie.vipOnly ? "VIP影片" : "普通影片"));
            movieDiv.append($("<p>").addClass("movie-info").text(`周播放量：${record.movieStats.weeklyViews}`));
            movieDiv.append($("<p>").addClass("movie-info").text(`月播放量：${record.movieStats.monthlyViews}`));
            movieDiv.append($("<p>").addClass("movie-info").text(`人气指标：${record.movieStats.likes}`));
            movieDiv.append($("<p>").addClass("movie-info").text(`好评指标：${record.movieStats.hotRank}`));
            movieDiv.append($("<p>").addClass("movie-info").text(`全部指标：${record.movieStats.totalRank}`));
            // 添加点击事件获取并显示视频
            movieDiv.click(function() {
                const movieId = $(this).attr("id"); // 获取电影 ID
                $.ajax({
                    url: `/movies/play/${movieId}`,
                    method: 'GET',
                    success: function(response) {
                        if (response.code === 200 && response.data && response.data.moviePlayer) {
                            const videoUrl = response.data.moviePlayer.videoUrl;
                            // 使用正则表达式匹配 src 属性值
                            const regex = /<iframe.*?src=["'](.+?)["']/;
                            const match = videoUrl.match(regex);
                            var videoSrc = "";
                            if (match && match.length > 1) {
                                videoSrc = match[1]; // 提取视频地址
                            }

                            // 在页面中显示视频
                            // 检查用户是否已经登录
                            var user = JSON.parse(sessionStorage.getItem("user"));
                            if (!user) {
                                // 用户未登录，提示需要登录
                                alert("请登录后观看影片");
                                // 重定向到登录页面
                                window.location.href = "/login";
                                return;
                            }
                            window.location.href = videoSrc;
                        } else {
                            // 用户不是会员，提示需要成为会员
                            alert("该影片为 VIP 影片，您需要成为会员才能观看");
                            // 重定向到会员注册页面
                            // window.location.href = "/membership";
                        }
                    },
                    error: function() {
                        alert("请求失败，请稍后重试");
                    }
                });
            });
            movieList.append(movieDiv);
        });
    }
});
